import type { PortForwardInfo } from "@linksaas-minapp/ssh-proxy-api";
import { Form, Input, Modal, Select,message } from "antd";
import { useState } from "react";
import { getPortforwardApi, getToken } from "../utils/client";

export interface ForwardModalProps {
    forwardClientId: string;
    onCancel: () => void;
    onOk: (pfInfo: PortForwardInfo) => void;
}

function ForwardModal(props: ForwardModalProps) {
    const [listen, setListen] = useState<"local" | "remote">("local");
    const [localAddr, setLocalAddr] = useState("");
    const [remoteAddr, setRemoteAddr] = useState("");

    const createPortForward = async () => {
        const api = getPortforwardApi();
        try {
            const pfId = await api.portforwardOpenPost({
                portforwardOpenPostRequest: {
                    token: getToken(),
                    id: props.forwardClientId,
                    remoteAddr,
                    localAddr,
                    listen,
                },
            });
            props.onOk({
                forwardId: pfId,
                remoteAddr,
                localAddr,
                listen,
            });
        } catch (e) {
            console.log(e);
            message.error("创建端口转发失败");
        }
    }

    return (
        <Modal open title="创建端口转发"
            okText="创建" okButtonProps={{ disabled: localAddr == "" || remoteAddr == "" }}
            onCancel={e => {
                e.stopPropagation();
                e.preventDefault();
                props.onCancel();
            }} onOk={e => {
                e.stopPropagation();
                e.preventDefault();
                createPortForward();
            }}>
            <Form labelCol={{ span: 6 }}>
                <Form.Item label="转发类型">
                    <Select value={listen} onChange={value => setListen(value)}>
                        <Select.Option value="local">转发服务器端口到本地</Select.Option>
                        <Select.Option value="remote">转发本地端口到服务器</Select.Option>
                    </Select>
                </Form.Item>
                <Form.Item label={listen == "local" ? "本地监听地址" : "本地转发地址"}>
                    <Input value={localAddr} onChange={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setLocalAddr(e.target.value.trim());
                    }} />
                </Form.Item>
                <Form.Item label={listen == "local" ? "服务器转发地址" : "服务器监听地址"}>
                    <Input value={remoteAddr} onChange={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setRemoteAddr(e.target.value.trim());
                    }} />
                </Form.Item>
            </Form>
        </Modal>
    );
}

export default ForwardModal;